package it.polimi.reTravelDream.beans;



import java.util.ArrayList;
import java.util.List;

import it.polimi.reTravelDream.dto.UserDTO;
import it.polimi.reTravelDream.eao.UserEAOLocal;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;


@ManagedBean(name="user")
@SessionScoped
public class UserBean {
	
	private List<UserDTO> allUserDTOs;
	
	@EJB
	private UserEAOLocal userAction;
	
	private UserDTO current;
	private String feedBackCreation="";
	private String errorEmail;
	private boolean isMessage;

	public UserBean(){
		this.current=new UserDTO();
		this.setAllUserDTOs(new ArrayList<UserDTO>());
	}
	
	@PostConstruct
	public void getAllUserDTO(){
		this.allUserDTOs=this.userAction.getAllUser();
	}
	
	public void create(){
		this.errorEmail="";
		this.feedBackCreation="";
		
		if (!this.checkEmail()) {
			this.errorEmail="this email is alredy present";
			this.feedBackCreation="Creation Error";
			return;
		}
		try {
			this.userAction.add(this.current);
			this.feedBackCreation="User Created!";
			this.current=new UserDTO();
		} catch (Exception e) {
			this.feedBackCreation="Creation Error";
		}
		this.isMessage=true;
		
	}
	
	private boolean checkEmail(){
		List<UserDTO> allUserDTOs=this.userAction.getAllUser();
		for(UserDTO userDTO:allUserDTOs){
			if (this.current.getEmail().equals(userDTO.getEmail())) {
				return false;
			}
		}
		return true;
	}
	
	
	public UserDTO getCurrent() {
		return current;
	}

	public void setCurrent(UserDTO current) {
		this.current = current;
	}
	public String getFeedBackCreation() {
		return feedBackCreation;
	}
	public void setFeedBackCreation(String feedBackCreation) {
		this.feedBackCreation = feedBackCreation;
	}
	public boolean isMessage() {
		return isMessage;
	}
	public void setMessage(boolean isMessage) {
		this.isMessage = isMessage;
	}
	public String getErrorEmail() {
		return errorEmail;
	}
	public void setErrorEmail(String errorEmail) {
		this.errorEmail = errorEmail;
	}
	public List<UserDTO> getAllUserDTOs() {
		return allUserDTOs;
	}
	public void setAllUserDTOs(List<UserDTO> allUserDTOs) {
		this.allUserDTOs = allUserDTOs;
	}

}
